package com.mqtt.controller;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

@RestController
@RequestMapping("/mqtt")
public class MqttController {

    /**
     * 1.设置MQTT数据集成请求体
     * {
     *     "clientid":${clientid},
     *     "topic":${topic},
     *     "payload":${payload},
     *     "timestamp":${timestamp}
     * }
     * 2.设置QMTT规则
     *    1.sql  SELECT * FROM  "t/a" 将主题为t/a的消息请求到当前接口
     *    2.设置如同上面1的请求体
     *    然后保存
     * ***注意：如果不定义请求体，则为原样（{"username":"test","topic":"t/a","timestamp":1755430975920,"qos":2,"publish_received_at":1755430975920,"pub_props":{"User-Property":{}},"peerhost":"127.0.0.1","payload":"{\n  \"x\": \"11111\"\n}","node":"emqx@127.0.0.1","metadata":{"rule_id":"rule_1knf"},"id":"00063C8E1FBF57BEF4430000791C0002","flags":{"retain":false,"dup":false},"event":"message.publish","clientid":"mqttx_cf6fe755"}）
     * @param request 也可以map接收
     * @throws IOException
     */
    @PostMapping("/save")
    //public void save(@RequestBody Map<Object,Object> body) throws IOException {
    public void save(HttpServletRequest request) throws IOException {
        // 获取微信回调参数
        InputStream inputStream= request.getInputStream();// 读取字节流
        InputStreamReader reader = new InputStreamReader(inputStream, "UTF-8");// 字节流转字符流
        BufferedReader in = new BufferedReader(reader);// 吧字符流放到字符缓冲流中读取，比 InputStreamReader 更快
        StringBuffer buffer = new StringBuffer();
        String line;
        while ((line = in.readLine()) != null){
            buffer.append(line);
        }
        // 关闭流
        in.close();
        inputStream.close();
        // {"clientid":mqttx_cf6fe755,"topic":t/a,"payload":{  "x": "10"},"timestamp":1755426394643}
        System.out.println(buffer.toString());
    }
}
